package com.ming.search;

/*
二分查找
 */
public class BinarySearch {
    public static void main(String[] args) {
        int arr[] = {1, 8, 10, 89, 1000, 1000, 1234};
        System.out.println(binarySearch(arr, 0, arr.length - 1, 10));
        System.out.println(binarySearch(arr, 10));
    }

    /*
    递归
     */
    private static int binarySearch(int[] arr, int left, int right, int findVal) {
        // 当 left > right 时， 说明递归整个数组， 但是没有找到
        if (left > right) {
            return -1;
        }
        int mid = (left + right) / 2;
        int midVal = arr[mid];
        if (findVal > midVal) { // 向 右递归
            return binarySearch(arr, mid + 1, right, findVal);
        } else if (findVal < midVal) { // 向左递归
            return binarySearch(arr, left, mid - 1, findVal);
        } else {
            return mid;
        }
    }

    /*
    非递归
     */
    private static int binarySearch(int[] arr, int findVal) {
        int left = 0, right = arr.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (arr[mid] > findVal) {
                right = mid - 1;
            } else if (arr[mid] < findVal) {
                left = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }
}
